package com.dy.basic.service.impl;

import com.dy.basic.constant.BaseConstants;
import com.dy.basic.service.VerifyCodeService;
import com.dy.basic.util.*;
import com.dy.user.domain.User;
import com.dy.user.dto.PhoneRegisterFormDto;
import com.dy.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    public static final String PHONEREGISTER = "register:";

    @Override
    public String graph(String key) throws IOException {
        // 1 判断值是否为空
        if (StringUtils.isEmpty(key)){
            throw new BusinessException("请输入参数");
        }
        // 2.调用工具类获取4位随机数
        String code = StrUtils.getComplexRandomString(4);
        // 3 将随机数设置到redis值中 ,key就是传过来的值，并设置5分钟过期
        redisTemplate.opsForValue().set(key,code, 5, TimeUnit.MINUTES);
        // 将code设置为图形并编码成base64;
        String s = VerifyCodeUtils.VerifyCode(100, 35, code);
        return s;
    }

    /**
     * 发送短信验证
     * @param phoneRegisterFormDto
     */
    @Override
    public void smsCode(PhoneRegisterFormDto phoneRegisterFormDto) {
        if ("binder:".equals(phoneRegisterFormDto.getType())){
            sendValid(phoneRegisterFormDto);
        } else {
            // 校验图片验证是否输入正确
            validate(phoneRegisterFormDto);
            // 发送验证码
            sendValid(phoneRegisterFormDto);
        }
    }

    /**
     * 发送验证码
     * @param phoneRegisterFormDto
     */
    private void sendValid(PhoneRegisterFormDto phoneRegisterFormDto) {
        // 3.查询电话号码是否被注册
        User user = userMapper.findByPhone(phoneRegisterFormDto.getPhone());
        if (null != user){
            throw new BusinessException("滚!!去登录");
        }
        // 4.判断手机验证码两次发送时间是否大于60秒
        Long registerexpire = redisTemplate.getExpire(String.format(phoneRegisterFormDto.getType(), phoneRegisterFormDto.getPhone()));
        if (registerexpire > 240){
            throw new BusinessException("请不要在60秒内重复登录");
        }
        // 5.是否需要重新发送生成手机验证码
        // 5.1.基于我们目前Redis中有没有手机验证码，有就用，没有就生成
        String code = (String) redisTemplate.opsForValue().get(String.format(phoneRegisterFormDto.getType(), phoneRegisterFormDto.getPhone()));
        if (StringUtils.isEmpty(code)){
            code = StrUtils.getComplexRandomString(4);
        }
        log.info(code);
        // 6.存到Redis中  key 手机号(带有区别标识符)   value  手机验证码
        redisTemplate.opsForValue().set(String.format(phoneRegisterFormDto.getType(), phoneRegisterFormDto.getPhone()),code,3,TimeUnit.MINUTES);
        // 7发送短信验证
    }

    /**
     * 验证参数
     * @param phoneRegisterFormDto
     */
    private void validate(PhoneRegisterFormDto phoneRegisterFormDto) {
        // 1.验证参数
        // 2.验证码是否输入正确 根据传过来的UUID查询Redis里面存的验证码和我们输入的是否一致
        String codeKey = (String) redisTemplate.opsForValue().get(phoneRegisterFormDto.getImageCodeKey());
        if (StringUtils.isEmpty(codeKey) || !codeKey.equalsIgnoreCase(phoneRegisterFormDto.getImageCodeValue())){
            throw new BusinessException("验证码错误");
        }
    }

    /**
     * 发送手机邮箱验证
     * @param email
     */
    @Override
    public String sendEmailCode(String email) {
        // 验证参数
        // 判断邮箱是否被注册
        User user = userMapper.findByEmail(email);
        String EmailUUID = PHONEREGISTER + email;
        if (null != user){
            throw new BusinessException("该邮箱已被注册,滚去登录");
        }
        // 60秒内不让重复点击
        Long expire = redisTemplate.getExpire(EmailUUID);
        if (expire > 240){
            throw new BusinessException("点你妈点傻呗!!!");
        }
        // 验证码没有后是否需要重新生成,,,,,过期的问题
        String code = (String) redisTemplate.opsForValue().get(EmailUUID);
        if (null  == code){
            // 生成UUID和邮箱验证码存到Redis UUID 存电话号码加一个标识  邮箱验证码调用工具类随机生成
            code = StrUtils.getComplexRandomString(4);
        }

        // 2.调用工具类获取4位随机数
        // 3 将随机数设置到redis值中 ,key就是传过来的值，并设置5分钟过期
        redisTemplate.opsForValue().set(EmailUUID ,code, 5, TimeUnit.MINUTES);

        // 发送邮箱
        String text = "【宠物乐园】: 您的邮箱注册验证码是:" +
                code;
        String people= email ;
        SendEmailUtil.send(text,people);
        // 把UUID返回给前端
        return EmailUUID;
    }
}
